﻿using System;
using TcpConnection;
using System.Net;
using System.Net.Sockets;

namespace ServerConsole
{
    class Program
    {
        static TcpServer server = null;
        static void Main(string[] args)
        {
            IPAddress address = null;
            int port = -1;

            while (true)
            {
                while(address != null)
                {
                    Console.WriteLine("请输入IP地址！");
                    string msg = Console.ReadLine();
                    if(!IPAddress.TryParse(msg , out address))
                    {
                        address = null;
                        Console.WriteLine("IP地址格式错误！");
                    }
                }   

                while (port != -1)
                {
                    Console.WriteLine("请输入端口！");
                    string msg = Console.ReadLine();
                    if(!int.TryParse(msg , out port) && port >=0)
                    {
                        port = -1;
                        Console.WriteLine("端口格式错误！");
                    }
                }

                server = new TcpServer(address , port);
                server.NewClinetConnectedEventHandler += Server_ClinetConnectedEventHandler;
                server.ClientDataReceivedEventHandler += Server_DataReceivedEventHanlder;
                server.ClientDisconnedtedEventHandler += Server_ClinetDisconnectedEventHandler;
                if(server.StartListen())
                {
                    break;
                }
                else    
                {
                    Console.WriteLine("端口监听失败！");
                }
            }

            while (true)
            {
                string message = Console.ReadLine();
                if(message == "break")
                {
                    return;
                }
            }
        }


        private static void Server_ClinetConnectedEventHandler(object sender , ClientConnectionChangedEventArgs e)
        {
            Console.WriteLine("客户端"+ e.Client.RemoteEndPoint + "接入!");
        }

        private static void Server_DataReceivedEventHanlder(object sender , ClientDataReceivedEventArgs e)
        {
            string message = System.Text.Encoding.Default.GetString(e.Data);
            Console.WriteLine(e.Client.RemoteEndPoint + ":" + message);
        }

        private static void Server_ClinetDisconnectedEventHandler(object sender , ClientConnectionChangedEventArgs e)
        {
            Console.WriteLine("客户端"+ e.Client.RemoteEndPoint + "断开!");
        }
    }
}
